package com.xhtech.base.network.config

import com.google.gson.annotations.SerializedName
import com.xhtech.base.network.ErrorNetWork
import com.yxh.lib_base.network.AppException
import com.yxh.lib_base.network.BaseResponse
import com.yxh.lib_base.state.ResultState

/**
 * @author yuanxh
 * @date :2023/6/30 13:08
 * @description:
 */
class ResultApi<T>(
    @SerializedName("code") private val code: Int,
    @SerializedName("detail") private val errorMsg: String,
    @SerializedName("data") private val mData: T?
) : BaseResponse<T>() {

    // 这里是示例，wanandroid 网站返回的 错误码为 0 就代表请求成功，请你根据自己的业务需求来改变
    override fun isSuccess() = code == ErrorNetWork.NET_WORK_SUCCESS.id

    override fun getCode(): Int = code

    override fun getMsg() = errorMsg

    override fun getData(): T = mData!!

    fun doSuccess(success: () -> Unit): ResultApi<T> {
        if (isSuccess()) {
            success.invoke()
        }
        return this
    }

    fun doError(error: (AppException) -> Unit): ResultApi<T> {
        if (!isSuccess()) {
            error.invoke(AppException(getCode(), getMsg() ?: ""))
        }
        return this
    }

}

